//
//  main.m
//  ProfilesManager
//
//  Created by Vescky on 14/10/27.
//  Copyright (c) 2014年 Vescky. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ProfileItem.h"


NSMutableArray *userProfiles;

#pragma mark - 声明函数
void showMenu();
void showCurrentUserProfiles();
void deleteProfile(NSString *d);
BOOL deleteItemByIndex(int pIndex);
BOOL deleteItem(NSDictionary *pDic);

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        scanf("");
        showMenu();
        while (1) {
            sleep(1);
            char input[100];
            scanf("%s",input);
            NSString *inString = [NSString stringWithUTF8String:input];
            deleteProfile(inString);
        }
    }
    return 0;
}

void showMenu() {
    system("clear");
    showCurrentUserProfiles();
    printf("A simple tool for XCode,ProfilesManager V1.0,Vescky 2014.10\n");
    printf("Usage:\n");
    printf("(1) type 'all' to delete all profiles except Apps123Team's.\n");
    printf("(2) use 'd' to delete profiles,such as 'd1,2,3'.'d' means only need to delete the listed profiles.\n");
    printf("(3) use 'r' to reserve profiles,such as 'r1,2,3'.'r' means delete all profiles except the listed profiles.\n");
    printf("Notice: No Space or other characters\n");
    printf("Please input cmd:");
}

void showCurrentUserProfiles() {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *profilesDir = [NSString stringWithFormat:@"%@/Library/MobileDevice/Provisioning Profiles",NSHomeDirectory()];
    NSError *err;
    NSArray *profiles = [fm contentsOfDirectoryAtPath:profilesDir error:&err];
    if (err) {
        NSString *sString = [NSString stringWithFormat:@"%@",err];
        printf("Error occured:%s",[sString UTF8String]);
        return;
    }
    if (!profiles || [profiles count] < 1) {
        printf("0 profile.");
        return;
    }
    
    int profileCounter = 0;
    userProfiles = [[NSMutableArray alloc] init];
    printf("======================================================================\n");
    for (int i = 0; i < profiles.count; i++) {
        NSString *profileName = [profiles objectAtIndex:i];
        NSString *profileNameLowercase = [profileName lowercaseString];
        if ([profileNameLowercase hasSuffix:@"mobileprovision"]) {
            profileCounter++;
            NSString *profilePath = [profilesDir stringByAppendingPathComponent:profileName];
            ProfileItem *pItem = [ProfileItem readProfileContent:profilePath];
            NSDictionary *profileDic = [[NSDictionary alloc] initWithObjectsAndKeys:pItem,@"content",profilePath,@"path",[NSNumber numberWithInt:i],@"index", nil];
            [userProfiles addObject:profileDic];
            printf("%2d --- AppName:%s BundleId:%s\n",profileCounter,[pItem.appName UTF8String],[pItem.bundleId UTF8String]);
        }
    }
    printf("Total %d profile%s.\n",profileCounter,(profileCounter > 1 ? "s" : ""));
    printf("======================================================================\n");

}

void deleteProfile(NSString *cmd) {
    if ([cmd isEqualToString:@"all"]) {
        printf("\nAre you sure to delete all profiles?\ntype 'yes' to delete,others to cancel:");
        char input[10];
        scanf("%s",input);
        NSString *inString = [NSString stringWithUTF8String:input];
        if ([inString isEqualToString:@"yes"]) {
            //delete all,except "Apps123 Team"
            for (int i = 0; i < userProfiles.count; i++) {
                NSDictionary *dic = [userProfiles objectAtIndex:i];
                ProfileItem *pItem = [dic objectForKey:@"content"];
                if (pItem && [pItem.appName isEqualToString:@"Apps123 Team"]) {
                    [userProfiles removeObject:dic];
                    break;
                }
            }
            
            //删除
            for (int i = 0; i < userProfiles.count; i++) {
                deleteItem([userProfiles objectAtIndex:i]);
            }
        }
    }
    else if ([cmd hasPrefix:@"d"]) {
        cmd = [cmd stringByReplacingOccurrencesOfString:@"d" withString:@""];
        NSArray *pArr = [cmd componentsSeparatedByString:@","];
        for (int i = 0; i < pArr.count ; i++) {
            int pIndex = [[pArr objectAtIndex:i] intValue];
            deleteItemByIndex(pIndex);
        }
        
    }
    else if ([cmd hasPrefix:@"r"]) {
        cmd = [cmd stringByReplacingOccurrencesOfString:@"r" withString:@""];
        NSArray *pArr = [cmd componentsSeparatedByString:@","];
        NSMutableArray *reserveList = [[NSMutableArray alloc] init];
        //查找保留的list
        for (int i = 0; i < pArr.count; i++) {
            int pIndex = [[pArr objectAtIndex:i] intValue];
            if (pIndex < userProfiles.count) {
                 NSDictionary *dic = [userProfiles objectAtIndex:i];
                if (dic) {
                    [reserveList addObject:dic];
                }
            }
        }
        //从数组中删掉保留的
        for (int i = 0; i < reserveList.count; i++) {
            NSDictionary *dic = [reserveList objectAtIndex:i];
            [userProfiles removeObject:dic];
        }
        //删除
        for (int i = 0; i < userProfiles.count; i++) {
            deleteItem([userProfiles objectAtIndex:i]);
        }
        
    }
    else {
        printf("Unknown command %s.\n",[cmd UTF8String]);
        return;
    }
    showMenu();
}

BOOL deleteItemByIndex(int pIndex) {
    if (pIndex < 1 || pIndex > userProfiles.count) {
        printf("invalid index %d.\n",pIndex);
        return 0;
    }
    
    for (int i = 0; i < userProfiles.count; i++) {
        NSDictionary *dic = [userProfiles objectAtIndex:i];
        if ([[dic objectForKey:@"index"] intValue] == pIndex) {
            return deleteItem(dic);
        }
    }
    
    printf("Profile not found.index:%d\n",pIndex);
    return 0;
}

BOOL deleteItem(NSDictionary *pDic) {
    if (!pDic) {
        return 0;
    }
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *profilePath = [pDic objectForKey:@"path"];
    if (!profilePath || profilePath.length < 1 || ![fm fileExistsAtPath:profilePath]) {
        return 0;
    }
    NSError *err;
    [fm removeItemAtPath:profilePath error:&err];
    if (err) {
        NSString *errString = [NSString stringWithFormat:@"%@",err];
        printf("Error occured:%s\n",[errString UTF8String]);
        return 0;
    }
    printf("Profile deleted:%s\n",[profilePath UTF8String]);
    return 1;
}
